var android3D0;  // Android机器人0
var android3D1;  // Android机器人1
var grass;       //草地
var river;       //河流
var lookatBall;  //视点中心球
var gl;
var sculpture;                                        //雕塑
var lookat = Array(70, 70, 70, 0, 0, 0, 0, 1, 0);     //视点
var lookatOffset = Array(0, 0, 0, 0, 0, 0, 0, 0, 0);  //视点的偏移量
var far = 150;                                        //视点到物点的距离
var currentAngle = [45, 55];  //视点的球行坐标系下的两个角
var perspective = new Array(30, 1, 1, 500);  //透视投影
var X_SCALE;                                 //根据画布变化的缩放系数
function main() {
  var canvas = document.getElementById('android3D');
  gl = WebGLUtils.setupWebGL(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  canvas.width = window.innerWidth - 30;
  canvas.height = window.innerHeight - 30;

  X_SCALE = canvas.height / canvas.width;
  gl.viewport(0, 0, canvas.width, canvas.height);
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.enable(gl.DEPTH_TEST);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  android3D0 = new android3D(
      canvas.height / canvas.width, [-3, 0, 0, 1], [0, 1, 0], 0, gl,
      'texImage1');
  android3D1 = new android3D(
      canvas.height / canvas.width, [3, 0, 0, 1], [0, 1, 0], 0, gl, null);

  android3D0.setEyeColor(0, 0, 0);
  android3D0.setBodyColor(0, 1, 0);
  android3D0.setHeadColor(0, 1, 0);
  android3D0.setArmColor(0, 1, 0);
  android3D0.setLegColor(0, 1, 0);
  android3D0.lookat = lookat;
  android3D1.lookat = lookat;
  android3D0.drawAndroid3D(gl);
  android3D1.drawAndroid3D(gl);

  grass = new Draw3D(gl, 'square', 'texImage2');
  river = new Draw3D(gl, 'square', 'river');
  grass.lookat = lookat;
  river.lookat = lookat;
  grass.drawSquare(
      gl, [-10, -2.7, -10], [-10, -2.7, 10], [10, -2.7, -10], [10, -2.7, 10]);
  river.drawSquare(
      gl, [10, -2.7, -10], [10, -2.7, 10], [20, -2.7, -10], [20, -2.7, 10]);

  sculpture = new Draw3D(gl, 'objFile');
  sculpture.drawByObjFile(gl, 'obj/ren_wu.obj');


  lookatBall = new Draw3D(gl, 'ball');
  lookatBall.drawBall(
      gl, new Array(lookat[3], lookat[4], lookat[5]), [0, 1, 0], 1, 0.5,
      [1, 1, 1]);
  var tick = function() {
    update();
    requestAnimationFrame(tick, canvas);
  };
  tick();

  /**
   * 注册鼠标滚动事件
   */
  if (document.addEventListener) {
    document.addEventListener('DOMMouseScroll', scrollFunc, false);
  }                                                          // W3C
  window.onmousewheel = document.onmousewheel = scrollFunc;  // IE/Opera/Chrome

  /**
   * 注册鼠标点击滑动时间
   */
  initEventHandlers(canvas);
}


var modelMatrix = new Matrix4();
/**
 * 图景更新
 */
function update() {
  /**
   * 视点的改变
   */
  var angleA = Math.PI * currentAngle[0] / 180;
  var angleB = Math.PI * currentAngle[1] / 180;
  lookat[2] = far * Math.sin(angleA) * Math.cos(angleB) + lookatOffset[2];
  lookat[0] = far * Math.sin(angleA) * Math.sin(angleB) + lookatOffset[0];
  lookat[1] = far * Math.cos(angleA);

  lookat[3] = lookatOffset[3];
  lookat[5] = lookatOffset[5];


  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  /**
   * Android机器人的重绘
   */
  android3D0.lookat = lookat;
  android3D0.perspective = perspective;
  android3D0.updateAndroid3D(gl);

  android3D1.lookat = lookat;
  android3D1.perspective = perspective;
  android3D1.updateAndroid3D(gl);


  /**
   * 草坪
   */
  grass.lookat = lookat;
  grass.perspective = perspective;
  for (var i = -100; i < 20; i += 20) {
    for (var j = -100; j < 100; j += 20) {
      modelMatrix.setScale(this.X_SCALE, 1, this.X_SCALE);
      modelMatrix.translate(i, 0, j);
      grass.MODEL_MATRIX = modelMatrix;
      grass.updateSquare(gl);
    }
  }
  for (var i = 40; i < 100; i += 20) {
    for (var j = -100; j < 100; j += 20) {
      modelMatrix.setScale(this.X_SCALE, 1, this.X_SCALE);
      modelMatrix.translate(i, 0, j);
      grass.MODEL_MATRIX = modelMatrix;
      grass.updateSquare(gl);
    }
  }

  /**
   * 雕塑
   */
  sculpture.lookat = lookat;
  sculpture.perspective = perspective;
  modelMatrix.setScale(this.X_SCALE, 1, this.X_SCALE);
  modelMatrix.translate(-10, -2.7, -100);
  sculpture.MODEL_MATRIX = modelMatrix;
  sculpture.updateByObjFile(gl);


  /**
   * 河流
   */
  river.lookat = lookat;
  river.perspective = perspective;
  for (var i = 0; i < 20; i += 10) {
    for (var j = -100; j < 100; j += 20) {
      modelMatrix.setScale(this.X_SCALE, 1, this.X_SCALE);
      modelMatrix.translate(i, 0, j);
      river.MODEL_MATRIX = modelMatrix;
      river.updateSquare(gl);
    }
  }
  /**
   * 视点球
   */
  lookatBall.lookat = lookat;
  lookatBall.perspective = perspective;
  modelMatrix.setScale(this.X_SCALE, 1, this.X_SCALE);
  lookatBall.MODEL_MATRIX = modelMatrix;
  lookatBall.updateBall(
      gl, new Array(lookat[3], lookat[4], lookat[5]), [0, 1, 0]);
}
/**
 * 键盘事件
 * 可用方向键控制视点的位置，左右方向，上下前后移动
 * 空格切换机器人
 * wasd控制机器人的移动
 * 1234键控制机器人的手臂摆动
 */
var androidIndex = 0;
var test = 0;
document.onkeydown = function(ev) {
  var ss = 10;
  switch (ev.keyCode) {
    case 37:  //  left
      lookatOffset[0] -= ss;
      lookatOffset[2] += ss;
      lookatOffset[3] -= ss;
      lookatOffset[5] += ss;
      break;
    case 39:  //  right
      lookatOffset[0] += ss;
      lookatOffset[2] -= ss;
      lookatOffset[3] += ss;
      lookatOffset[5] -= ss;
      break;
    case 38:  //  up
      lookatOffset[0] -= ss;
      lookatOffset[2] -= ss;
      lookatOffset[3] -= ss;
      lookatOffset[5] -= ss;
      break;
    case 40:  // down
      lookatOffset[0] += ss;
      lookatOffset[2] += ss;
      lookatOffset[3] += ss;
      lookatOffset[5] += ss;
      break;
    case 32:  // 空格切换
      if (androidIndex == 0) {
        androidIndex = 1;
      } else {
        androidIndex = 0;
      }
      break;
    default:
      if (androidIndex == 0) {
        android3D0.keydown(ev);
      }
      if (androidIndex == 1) {
        android3D1.keydown(ev);
      }
      break;
  }
};


/**
 * 鼠标滚动事件
 * 控制图景的缩放
 */
var scrollFunc = function(e) {
  var ss = 20;
  e = e || window.event;
  if (e.wheelDelta == 120 || e.detail == -3) {
    far += ss
    perspective[3] += 100;
  }
  if (e.wheelDelta == -120 || e.detail == 3) {
    if (perspective[3] > 100) {
      far -= ss;
      perspective[3] -= 100;
    }
  }
};


/**
 * 画布改变时调用，改变缩放值以适用画布大小
 */
function windowChange() {
  var canvas = document.getElementById('android3D');
  canvas.width = window.innerWidth - 30;
  canvas.height = window.innerHeight - 30;
  gl.viewport(0, 0, canvas.width, canvas.height);
  X_SCALE = canvas.height / canvas.width;
  android3D0.X_SCALE = X_SCALE;
  android3D1.X_SCALE = X_SCALE;
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  update();
}


/**
 * 鼠标点击滑动
 * 鼠标跟踪球
 */
function initEventHandlers(canvas) {
  var lastX = -1;
  var lastY = -1;
  var mousedown = false;
  canvas.onmousemove = function(ev) {
    var x = ev.clientX, y = ev.clientY;
    if (mousedown) {
      var factor = 100 / canvas.height;
      var dx = (x - lastX) / 100;
      var dy = (y - lastY) / 100;
      currentAngle[0] = Math.max(Math.min(currentAngle[0] + dy, 90.0), -90.0);
      currentAngle[1] = currentAngle[1] + dx;
    }
  };
  canvas.onmousedown = function(ev) {

    var x = ev.clientX, y = ev.clientY;
    var rect = ev.target.getBoundingClientRect();
    if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
      lastX = x;
      lastY = y;
      mousedown = true;
    }

  };
  canvas.onmouseup = function() {
    mousedown = false;
    lastX = -1;
    lastY = -1;
  };
}